package com.hksj.slm.service;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.hksj.cbm.service.DeviceInstanceService;
import com.hksj.cbm.vo.SpaceModelVO;
import com.hksj.common.core.model.Rest;
import com.hksj.slm.dto.LinkLightingDTO;
import com.hksj.slm.entity.LinkLighting;
import com.hksj.slm.mapper.LinkLightingMapper;
import com.hksj.slm.query.LightingDeviceQuery;
import com.hksj.slm.query.LinkLightingQuery;
import com.hksj.slm.vo.LightingDeviceVO;
import com.hksj.slm.vo.LinkLightingVO;
import com.hksj.slm.vo.ModelPropertiesVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Type;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * description：照明设备关联服务类
 *
 * @author niexiang
 * @date 2024/08/26 15:41
 */
@Service
public class LinkLightingService extends ServiceImpl<LinkLightingMapper, LinkLighting> {

    @Autowired
    private DeviceInstanceService deviceInstanceService;

    @Autowired
    private LinkLightingMapper linkLightingMapper;


    @Transactional
    public Rest<String> saveLinkLighting(LinkLightingDTO dto) {
        //先删除后新增
        linkLightingMapper.delete(Wrappers.<LinkLighting>lambdaQuery()
                .eq(LinkLighting::getDeviceId, dto.getDeviceId())
                .eq(LinkLighting::getProperty, dto.getProperty()));
        LinkLighting entity = new LinkLighting();
        BeanUtils.copyProperties(dto, entity);
        if (this.save(entity)){
            return Rest.ok("新增成功");
        }
        return Rest.fail("新增失败");
    }

    @Transactional
    public Rest<String> updateLinkLighting(LinkLightingDTO dto) {
        LinkLighting entity = new LinkLighting();
        BeanUtils.copyProperties(dto, entity);
        if (this.updateById(entity)){
            return Rest.ok("修改成功");
        }
        return Rest.fail("修改失败");
    }

    @Transactional
    public Rest<String> deleteLinkLighting(LinkLightingDTO dto) {
        // 删除符合条件的记录
        int rowsAffected = linkLightingMapper.delete(Wrappers.<LinkLighting>lambdaQuery()
                .eq(LinkLighting::getDeviceId, dto.getDeviceId())
                .eq(LinkLighting::getProperty, dto.getProperty()));

        // 根据受影响的行数判断删除是否成功
        if (rowsAffected > 0) {
            return Rest.ok("删除成功");
        } else {
            return Rest.fail("删除失败");
        }
    }

    /**
     * description：查询照明设备关联列表
     *
     * @param query
     * @return {@code List<LinkLightingVO> }
     * @author niexiang
     * @date 2024/08/26 15:42
     */
    @Transactional
    public List<LinkLightingVO> queryLinkLightingList(LinkLightingQuery query) {
        List<LinkLightingVO> list = this.queryLinkLightingJson(query);
        List<LinkLightingVO> childList = linkLightingMapper.queryLinkLightingList(query);
        // 处理子属性
        if (!CollectionUtils.isEmpty(childList)){
            Map<String, LinkLightingVO> map = childList.stream().collect(Collectors.toMap(LinkLightingVO::getProperty, item -> item));
            list.forEach(item -> {
                LinkLightingVO child = map.get(item.getProperty());
                if (Objects.nonNull(child)){
                    BeanUtils.copyProperties(child, item);
                }
            });
        }

        return list;
    }

    /**
     * description：查询照明设备模型列表
     *
     * @param query
     * @return {@code List<LinkLightingVO> }
     * @author niexiang
     * @date 2024/08/26 15:42
     */
    public List<LinkLightingVO> queryLightingModelList(LinkLightingQuery query) {
        return linkLightingMapper.queryLightingModelList(query);
    }

    public List<LinkLightingVO> queryLinkLightingJson(LinkLightingQuery query) {
        // 查询照明设备关联列表
        LightingDeviceVO vo = linkLightingMapper.queryLightingDeviceById(query);

        // 解析物模型
        Gson gson = new Gson();
        JsonObject root1 = vo.getDeriveMetadata() != null ? JsonParser.parseString(vo.getDeriveMetadata()).getAsJsonObject() : new JsonObject();
        JsonObject root2 = vo.getMetadata() != null ? JsonParser.parseString(vo.getMetadata()).getAsJsonObject() : new JsonObject();
        JsonArray properties1 = root1.has("properties") ? root1.getAsJsonArray("properties") : new JsonArray();
        JsonArray properties2 = root2.has("properties") ? root2.getAsJsonArray("properties") : new JsonArray();
        JsonArray mergedProperties = new JsonArray();
        mergedProperties.addAll(properties1);
        mergedProperties.addAll(properties2);
        // 定义 TypeToken 对象以获取 List<ModelPropertiesVO> 的 Type 信息
        Type modelListType = new TypeToken<List<ModelPropertiesVO>>() {}.getType();
        // 将 JsonArray 转换为 List<ModelPropertiesVO>
        List<ModelPropertiesVO> modelList = gson.fromJson(mergedProperties, modelListType);
        vo.setMetadataPropertyList(modelList);

        // 将属性信息转换为 LinkLighting 实体列表

        return modelList.stream()
                .filter(i -> !i.getId().contains("dwkg"))
                .map(model -> {
                    LinkLightingVO entity = new LinkLightingVO();
                    entity.setDeviceId(vo.getDeviceId());
                    entity.setProperty(model.getId());
                    return entity;
                })
                .sorted(Comparator.comparing(LinkLightingVO::getProperty)) // 使用 sorted 进行排序
                .collect(Collectors.toList());

    }
}
